package com.sxhuayuan.parking.queue.msg;

import java.io.Serializable;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;

/**
 * (延时)消息对象
 */
public class QueueMsg implements Serializable {

	private static final long serialVersionUID = -3366102580965221890L;

	private String topic;

	private Long id;

	// 执行时间,时间戳
	private long delayTime;
	// 消息内容
	private String body;

	// 失败重试机制
	private Integer[] retryPlan;
	// 重试次数
	private Integer retryTimes = 0;

	public String getTopic() {
		return topic;
	}

	public void setTopic(String topic) {
		this.topic = topic;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public long getDelayTime() {
		return delayTime;
	}

	public void setDelayTime(long delayTime) {
		this.delayTime = delayTime;
	}

	// /**
	// * 执行超时时间，秒
	// */
	// public int getTtr() {
	// return ttr;
	// }
	//
	// /**
	// * 执行超时时间，秒
	// */
	// public void setTtr(int ttr) {
	// this.ttr = ttr;
	// }

	public String getBody() {
		return body;
	}

	public void setBody(String body) {
		this.body = body;
	}

	public Integer[] getRetryPlan() {
		return retryPlan;
	}

	public void setRetryPlan(Integer[] retryPlan) {
		this.retryPlan = retryPlan;
	}

	public Integer getRetryTimes() {
		return retryTimes;
	}

	public void setRetryTimes(Integer retryTimes) {
		this.retryTimes = retryTimes;
	}

	/**
	 * 是否已经超过最大重试次数
	 * 
	 * @return
	 */
	@JSONField(serialize = false)
	public boolean isDeadMsg() {
		return retryPlan == null || retryTimes >= retryPlan.length;
	}

	/**
	 * 获取下一次执行超时时间
	 * 
	 * @return
	 */
	@JSONField(serialize = false)
	public Integer nextTtr() {
		if (retryPlan == null)
			return 0;
		return retryPlan[retryTimes++];
	}

	@Override
	public String toString() {
		final StringBuilder sb = new StringBuilder("DelayQueueMsg{");
		sb.append("id=").append(id);
		sb.append(", topic='").append(topic).append('\'');
		sb.append(", delayTime=").append(delayTime);
		// sb.append(", ttr=").append(ttr);
		sb.append(", body='").append(body).append('\'');
		sb.append(", retryPlan='").append(StringUtils.join(retryPlan, ",")).append('\'');
		sb.append(", retryTimes=").append(retryTimes);
		sb.append('}');
		return sb.toString();
	}

	@JSONField(serialize = false)
	public byte[] getBytes() {
		return JSON.toJSONString(this).getBytes();
	}
}
